﻿using System.Collections;
using System.Windows.Forms;

namespace MusicPage
{
    public class MusicPageViewSorter : IComparer
    {
        private int columnIndex;
        private bool reverse = false;

        public MusicPageViewSorter()
        {
            columnIndex = 0;
        }

        public void SetColumnSorting(int column)
        {
            if (this.columnIndex == column)
            {
                this.reverse = !this.reverse;
            }
            this.columnIndex = column;
        }

        #region IComparer Members

        public int Compare(object x, object y)
        {
            var lvi1 = x as ListViewItem;
            var lvi2 = y as ListViewItem;

            if (lvi1 != null && lvi2 != null && lvi1.SubItems.Count > columnIndex && lvi2.SubItems.Count > columnIndex)
            {
                int result = lvi1.SubItems[columnIndex].Text.CompareTo(lvi2.SubItems[columnIndex].Text);
                if (reverse)
                {
                    result = -result;
                }
                return result;
            }
            else
            {
                return 0;
            }
        }

        #endregion
    }
}